package com.dqlp.yf.rabbitmq.sender;

import com.dqlp.yf.rabbitmq.constant.MqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @program: rabbitmq
 * @description: 产生私信队列发送者
 * @author: andy
 * @create: 2019-09-07 16:13
 */
@Component
@Slf4j
public class DlxSender implements RabbitTemplate.ReturnCallback,RabbitTemplate.ConfirmCallback {

    final RabbitTemplate rabbitTemplate;

    @Autowired
    public DlxSender(RabbitTemplate rabbitTemplate) {
        rabbitTemplate.setConfirmCallback(this::confirm);
        rabbitTemplate.setReturnCallback(this::returnedMessage);
        this.rabbitTemplate = rabbitTemplate;
    }

    public void sendMessage(String msg,String routingKey) {
        for (int i = 0; i <= 50000; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("num", i);
            MessageProperties properties = new MessageProperties();
            properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            properties.setHeader("num",i);
            // properties.setExpiration("5000"); // 设置有效期毫秒 过期自动丢弃
            Message message = new Message((msg+i).getBytes(), properties);
            String a = UUID.randomUUID().toString();
            CorrelationData correlationData = new CorrelationData(String.valueOf(i));
            rabbitTemplate.convertAndSend(MqConstant.DIRECT_EXCHANGE, MqConstant.DIRECT_ROUTERKEY, message,correlationData);
        }
    }

    @Override
    public void confirm( CorrelationData correlationData, boolean ack,  String cause) {
        log.info(correlationData+"&&&&&&&&&&&&&&&&&");
        log.info("direct队列收到信号");
        if (ack) {
            log.info("direct队列成功");
        } else {
            log.info("direct队列失败，出现异常");
        }

    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("return exchange: {}, routingKey: {}, replyCode: {}, replyText: {}",
                exchange, routingKey, replyCode, replyText);
    }
}
